<template>
  <div class="app-container">
    <div class="search_container_warp">
      <el-form
        ref="queryFormRef"
        class="search_container"
        :model="queryParams"
        :inline="true"
      >
        <el-form-item label="赛项名称" prop="matchCode">
          <el-select
            v-model="queryParams.matchCode"
            @change="changeFn"
            style="width: 360px"
          >
            <el-option
              v-for="item in eventDataList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="组别" prop="matchGroup">
          <el-select
            style="width: 120px"
            v-model="queryParams.matchGroup"
            @change="matchGroupChangeFn"
          >
            <el-option
              v-for="item in matchGroupOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="downloadTemplateFn">
            <!-- <i-ep-search /> -->
            导出成绩
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        class="customTableClass"
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
        :span-method="objectSpanMethod"
      >
        <!-- <el-table-column label="序号" type="index" align="center" width="60" /> -->
        <el-table-column label="序号" width="60" prop="index" align="center" />
        <el-table-column
          label="学校名称"
          prop="schoolName"
          align="center"
          min-width="160"
        />
        <el-table-column
          label="组别"
          prop="matchGroupName"
          align="center"
          width="80"
        />
        <el-table-column
          label="赛队编号"
          prop="teamNumber"
          align="center"
          width="90"
        />

        <el-table-column
          label="赛队总分"
          prop="totalScore"
          align="center"
          width="85"
        />
        <el-table-column
          label="平均分"
          prop="average"
          align="center"
          width="80"
        />
        <el-table-column
          label="赛队成绩(30%)"
          prop="teamScore"
          align="center"
          width="120"
        />
        <el-table-column 
				  label="排名" 
					prop="rank" 
					align="center" 
					width="75"
				/>
        <el-table-column					
          label="姓名"
          prop="stuName"
          align="center"
          width="100"
        />
        <el-table-column
          label="理论分数"
          prop="score"
          align="center"
          width="90"
        >
          <template #default="scope">
            <span class="clickLinkClass" @click="gotoPage(scope.row)">
              {{ scope.row.score }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remark"
          align="center"
          min-width="100"
        />
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { getEventList } from "@/api/examManagement";
import { getDictionaryPage } from "@/api/examManagement";
import { getTheoreticalScoreList, exportGrades } from "@/api/examProgress";
import { ItemPageVO, Options } from "@/api/examProgress/types";
import { computeHeiht, mergeCalculation } from "@/utils/index";
const router = useRouter();

defineOptions({
  name: "TheoreticalScore",
  inheritAttrs: false,
});
const queryFormRef = ref(ElForm);
const dataList = ref<ItemPageVO[]>([]);
const originaldataList = ref<ItemPageVO[]>([]);
const groupOptions = ref<Options[]>([]);
const eventDataList = ref<any[]>([]);
const matchGroupOptions = ref<any[]>([]);
const loading = ref(false);

const queryParams = reactive<any>({
  matchCode: "",
  matchGroup: "",
  matchId: "",
});

function downloadTemplateFn() {
  const item = eventDataList.value.find((v) => {
    return v.value === queryParams.matchCode;
  });
  const text = item?.label || "";
  if (!queryParams.matchId) {
    return;
  }
  exportGrades(queryParams.matchId).then((res) => {
    const blob = new Blob([res.data], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    const downloadLink = document.createElement("a");
    downloadLink.href = url;
    downloadLink.download = text + "成绩.xlsx";
    downloadLink.click();
  });
}

// 选择赛项名称
function changeFn(value: any) {
  queryParams.matchCode = value;
  eventDataList.value.forEach((v) => {
    if (v.value === value) {
      // 过滤事项对应的组别
      matchGroupOptions.value = v.matchGroupList.map((j: any) => {
        const { matchGroup, matchId } = j;
        // matchId // 赛项ID
        let item = { value: matchGroup, label: matchGroup, matchId: matchId };
        // 组装组别的key value
        groupOptions.value.forEach((k) => {
          if (matchGroup === k.value) {
            item.label = k.label;
          }
        });
        return item;
      });
    }
  });
  // 默认选择第一个组别
  if (matchGroupOptions.value?.length) {
    queryParams.matchGroup = matchGroupOptions.value[0].value;
    // queryParams.matchId = matchGroupOptions.value[0].matchId;
    matchGroupChangeFn(queryParams.matchGroup);
  }
}

// 选择组别
function matchGroupChangeFn(value: any) {
  matchGroupOptions.value.forEach((v) => {
    if (value === v.value) {
      queryParams.matchId = v.matchId;
    }
  });
  handleQuery();
}
function gotoPage(row: any) {
  // router.push(`/systemManagement/examPapersDetails`);
  router.push(`/systemManagement/examPapersDetails?id=${row.examId}`);
}

/** 查询 */
function handleQuery() {
  loading.value = true;
  getTheoreticalScoreList({ id: queryParams.matchId })
    .then(({ data }) => {
      let indexList = new Map();
      data.forEach((item) => {
        const name = item.teamNumber + item.schoolName;
        if (!indexList.has(name)) {
          indexList.set(name, indexList.size + 1);
        }
        item.matchGroup += "";
        // 组别转name
        groupOptions.value?.forEach((v: any) => {
          if (v.value === item.matchGroup) {
            item.matchGroupName = v.label;
          }
        });
      });
      data.forEach((item) => {
        const name = item.teamNumber + item.schoolName;
        if (indexList.has(name)) {
          item.index = indexList.get(name);
          // item.matchGroupNameIndex = indexList.get(name);
        }
      });
      dataList.value = data;
      originaldataList.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}
/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

async function getCommonParameters() {
  let { data } = await getDictionaryPage("MATCH_GROUP", 1);
  groupOptions.value = data.map((v: any) => {
    return {
      label: v.name,
      value: v.myKey,
    };
  });
  // 获取事项
  await getEventList()
    .then(({ data }) => {
      let codeList = new Map();
      let listData = data.map((item: any) => {
        item.matchGroup += ""; // 统一格式 字符串
        item.value = item.matchCode;
        item.label = item.matchName;
        // 把赛项下的组别收集起来
        if (!codeList.has(item.matchCode)) {
          codeList.set(item.matchCode, [
            { matchGroup: item.matchGroup, matchId: item.id },
          ]);
        } else {
          let list = codeList.get(item.matchCode);
          list.splice(list.length, 0, {
            matchGroup: item.matchGroup,
            matchId: item.id,
          });

          codeList.set(item.matchCode, list);
        }
        return item;
      });
      // 把赛项下的组别赋值
      listData.forEach((item: any) => {
        if (codeList.has(item.matchCode)) {
          item.matchGroupList = codeList.get(item.matchCode);
        }
      });
      // 过滤重复赛项
      let resultList = new Map();
      listData.forEach((v: any) => {
        if (!resultList.has(v.matchCode)) {
          resultList.set(v.matchCode, v);
        }
      });

      // eventDataList.value = [...listData];
      eventDataList.value = [...resultList.values()];
      changeFn(eventDataList.value[0].value);
    })
    .finally(() => {
      loading.value = false;
    });
  handleQuery();
}

interface SpanMethodProps {
  row: any;
  rowIndex: number;
  columnIndex: number;
}
/**
 * @param row 当前行
 * @param column 当前列
 * @param rowIndex 当前行号，第几行
 * @param columnIndex 当前列号
 * @returns {{rowspan: number, colspan: number}}
 */
const objectSpanMethod = ({ row, rowIndex, columnIndex }: SpanMethodProps) => {
  if (columnIndex === 0) {
    let data: any = [...dataList.value];
    const { intRowSpan } = mergeCalculation(data, rowIndex, "index");
    return {
      rowspan: intRowSpan,
      colspan: intRowSpan == 0 ? 0 : 1, // 如果不合并行，就返回0，说白了就不合并
    };
  } else if (columnIndex === 1) {
    let data: any = [...dataList.value];
    const { intRowSpan } = mergeCalculation(data, rowIndex, "index");
    return {
      rowspan: intRowSpan,
      colspan: intRowSpan == 0 ? 0 : 1, // 如果不合并行，就返回0，说白了就不合并
    };
  } else if (columnIndex === 2) {
    let data: any = [...dataList.value];
    const { intRowSpan } = mergeCalculation(data, rowIndex, "index");
    return {
      rowspan: intRowSpan,
      colspan: intRowSpan == 0 ? 0 : 1, // 如果不合并行，就返回0，说白了就不合并
    };
  } else if (columnIndex === 3) {
    let data: any = [...dataList.value];
    const { intRowSpan } = mergeCalculation(data, rowIndex, "index");
    return {
      rowspan: intRowSpan,
      colspan: intRowSpan == 0 ? 0 : 1, // 如果不合并行，就返回0，说白了就不合并
    };
  } else if (columnIndex === 4) {
    let data: any = [...dataList.value];
    const { intRowSpan } = mergeCalculation(data, rowIndex, "index");
    return {
      rowspan: intRowSpan,
      colspan: intRowSpan == 0 ? 0 : 1, // 如果不合并行，就返回0，说白了就不合并
    };
  } else if (columnIndex === 5) {
    let data: any = [...dataList.value];
    const { intRowSpan } = mergeCalculation(data, rowIndex, "index");
    return {
      rowspan: intRowSpan,
      colspan: intRowSpan == 0 ? 0 : 1, // 如果不合并行，就返回0，说白了就不合并
    };
  } else if (columnIndex === 6) {
    let data: any = [...dataList.value];
    const { intRowSpan } = mergeCalculation(data, rowIndex, "index");
    return {
      rowspan: intRowSpan,
      colspan: intRowSpan == 0 ? 0 : 1, // 如果不合并行，就返回0，说白了就不合并
    };
  } else if (columnIndex === 7) {
    let data: any = [...dataList.value];
    const { intRowSpan } = mergeCalculation(data, rowIndex, "index");
    return {
      rowspan: intRowSpan,
      colspan: intRowSpan == 0 ? 0 : 1, // 如果不合并行，就返回0，说白了就不合并
    };
  }
};

onMounted(() => {
  getCommonParameters();
  computeHeiht();
});
</script>
